/*
 * Created on Oct 4, 2003
 *
 * Mihai Postelnicu
 *
 */
package ro.gateway.aida.struts.action;

import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.actions.TilesAction;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserDB;
import ro.gateway.aida.usr.messaging.LPDRelay;
import ro.gateway.aida.utils.HttpUtils;
import ro.xblue.translator.TranslatorUtils;
import ro.xblue.translator.Translator_DB;


/**
 * @author Mihai Postelnicu
 * PasswordRecoveryAction
 *
 * */
public class PasswordRecoveryAction extends TilesAction {
	
	private String getRandomPassword() {
		Random r=new Random(System.currentTimeMillis());
		int pwd=r.nextInt();
		if (pwd<0) pwd=-pwd;
		String spwd=Integer.toString(pwd);
		return spwd;
	}
	
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            String mymail = request.getParameter("mymail");
            String mode = request.getParameter("mode");
            
            ServletContext sc = getServlet().getServletContext();
			PersistenceToken token = PersistenceManager.tokenLookup( sc );
			String lang = TranslatorUtils.getCurrentLanguage(request,
								sc).getLanguage();
            
			Translator_DB tdb=Translator_DB.getManager(token);
			
			String ctx = request.getContextPath();

            if ("form".equals(mode)) {
                return mapping.findForward("sendform");
            }

			if (mymail==null) return mapping.findForward("fail ");
            UserDB udb=UserDB.getManager(token);
            User u=udb.getByEmail(mymail.trim());
            String newpass=getRandomPassword();
            udb.changePass(u.getId(),HttpUtils.getHash(newpass));
            if (u==null) return mapping.findForward("nouser");
            StringBuffer sb=new StringBuffer();
            sb.append(tdb.getMessage(lang,"login","login.passlogin")).append("<p>")
            .append(tdb.getMessage(lang,"login","login.usr")).append(u.getLogin()).append("<p>")
            .append(tdb.getMessage(lang,"login","login.pass")).append(newpass);
            
            LPDRelay lpdr=LPDRelay.getManager(token);
            lpdr.sendMail(tdb.getMessage(lang,"login","login.emailsubject"),sb.toString(),u.getEmail());
            
            return mapping.findForward("mailsent");
            
        } catch (Exception e) {
            return mapping.findForward("fail");
        }
    }
}
